package com.bestcem.xm.script.service.impl;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.member.mq.message.OrgCreatedMessage;
import com.bestcem.xm.member.mq.message.UserMessage;
import com.bestcem.xm.member.service.MemberMqHandler;
import com.bestcem.xm.script.grpc.client.ScriptUserClient;
import com.bestcem.xm.script.service.InitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 初始化服务
 * @date 2021-11-11
 */
@Slf4j
@Service("initService")
public class InitServiceImpl implements InitService {

    @Value("${app.script.secret:jLfi5gxF7aJpomC}")
    private String scriptSecret;

    /**
     * 用户客户端
     */
    @Autowired
    private ScriptUserClient scriptUserClient;

    @Autowired
    private MemberMqHandler memberMqHandler;

    @Override
    public ServiceResult<String> init(String secret, String orgCode) {
        if (!StringUtils.equals(scriptSecret, secret)) {
            return ServiceResult.fail("密钥错误");
        }

        // 获取企业标识
        ServiceResult<String> result = scriptUserClient.getOrgId(orgCode);
        if (!result.isSuccess()) {
            return ServiceResult.fail(result.getMsg());
        }
        String orgId = result.getData();

        // 初始化可见范围
        OrgCreatedMessage orgCreatedMessage = new OrgCreatedMessage();
        orgCreatedMessage.setId(orgId);
        boolean success = memberMqHandler.createMemberDisplayRange(orgCreatedMessage);
        if (!success) {
            return ServiceResult.fail("初始化可见范围失败");
        }
        // 初始化默认标签组
        success = memberMqHandler.createDefaultLabelGroup(orgCreatedMessage);
        if (!success) {
            return ServiceResult.fail("初始化默认标签组失败");
        }

        // 获取管理用户标识
        result = scriptUserClient.getAdminUserId();
        if (!result.isSuccess()) {
            return ServiceResult.fail(result.getMsg());
        }
        String userId = result.getData();

        UserMessage userMessage = new UserMessage();
        userMessage.setId(userId);
        try {
            memberMqHandler.createInnerMemberByCreateUser(userMessage);
        } catch (Exception e) {
            log.error("初始化内部联系人失败", e);
            return ServiceResult.fail("初始化默认标签组失败");
        }
        return ServiceResult.success("Success");
    }
}
